package org.tamal.struts;


import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;
import org.tamal.annotation.AllowHttpGet;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * This Interceptor skips execution of HTTP get request.
 * @author Tamal Kanti Nath
 */
public final class SkipHttpGetInterceptor implements Interceptor {

    private static final long serialVersionUID = -2695252753195114827L;
    private final transient Logger log = Logger.getLogger(getClass().getName());

    @Override
    public void destroy() {
        log.info("destroy");
    }

    @Override
    public void init() {
        log.info("init");
    }

    /**
     * This method skips execution of action on HTTP GET request. Otherwise it
     * process the action.
     * @param invocation the action invocation
     * @return INPUT or the return of action
     * @throws Exception any system-level error, as defined in
     *     {@link com.opensymphony.xwork2.Action#execute()}.
     */
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        HttpServletRequest request = (HttpServletRequest) invocation
                .getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
        if ("GET".equals(request.getMethod())
                && !StrutsUtils.isAnnotated(invocation, AllowHttpGet.class)) {
            return Action.INPUT;
        }
        return invocation.invoke();
    }

}
